import {reactive} from 'vue';

type CommandCallback = (data: any) => void;
type MessageData = {
    platform: string;
    cmd: string;
    data?: any;
};

class IframeMessageHandler {
    private cmdMap: Map<string, CommandCallback> = new Map();

    constructor(private platform: string) {
        window.addEventListener('message', this.handleMessage.bind(this));
    }

    public postMsg(cmd: string, data: any = null) {
        if (data !== null && typeof data !== 'string') {
            data = JSON.stringify(data);
        }
        uni.getEnv((res: any) => {
            if (!res.h5) {
                uni.postMessage({
                    data: {
                        platform: this.platform,
                        cmd,
                        data,
                    },
                });
            } else {
                window.postMessage(
                    {
                        data:{platform: this.platform, cmd, data},
                    },
                    '*'
                );
            }
        })
    }

    public watchCmd(cmd: string, callback: CommandCallback) {
        this.cmdMap.set(cmd, callback);
    }

    private handleMessage(event: MessageEvent<MessageData>) {
        const {data} = event;
        // 只处理来自其他平台的消息
        if (data.platform !== this.platform) {
            try {
                if (typeof data.data === 'string') {
                    data.data = JSON.parse(data.data);
                }
                const callback = this.cmdMap.get(data.cmd);
                if (callback) {
                    callback(data.data);
                }
            } catch (error) {
                console.error('Error handling message:', error);
            }
        }
    }
}

// 创建全局单例
const messageHandlerInstance = new IframeMessageHandler('child-mobile');
export default messageHandlerInstance;
